import React, { useCallback } from 'react'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { Row, Col, Empty, Spin } from 'antd'
import { DraggableSceneCard } from '../SceneCard/DraggableSceneCard'
import { AddSceneCard } from '../SceneCard/AddSceneCard'
import { StoryboardScene } from '../../../types/document'

export interface SceneGridProps {
  scenes: StoryboardScene[]
  selectedSceneId?: string | null
  loading?: boolean
  onSceneSelect?: (sceneId: string) => void
  onSceneEdit?: (sceneId: string) => void
  onSceneDelete?: (sceneId: string) => void
  onSceneDuplicate?: (sceneId: string) => void
  onScenePreview?: (sceneId: string) => void
  onSceneMove?: (fromIndex: number, toIndex: number) => void
  onSceneAdd?: () => void
}

/**
 * 场景网格组件
 * 显示所有场景卡片，支持拖拽排序和各种操作
 */
export const SceneGrid: React.FC<SceneGridProps> = ({
  scenes,
  selectedSceneId,
  loading = false,
  onSceneSelect,
  onSceneEdit,
  onSceneDelete,
  onSceneDuplicate,
  onScenePreview,
  onSceneMove,
  onSceneAdd
}) => {
  // 处理场景移动
  const handleSceneMove = useCallback((fromIndex: number, toIndex: number) => {
    onSceneMove?.(fromIndex, toIndex)
  }, [onSceneMove])

  // 响应式列配置
  const getColSpan = () => ({
    xs: 24,  // 移动端：1列
    sm: 12,  // 小屏：2列
    md: 8,   // 中屏：3列
    lg: 6,   // 大屏：4列
    xl: 6,   // 超大屏：4列
    xxl: 4   // 超超大屏：6列
  })

  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        minHeight: '400px' 
      }}>
        <Spin size="large" tip="加载场景列表...">
          <div style={{ minHeight: '200px' }} />
        </Spin>
      </div>
    )
  }

  if (scenes.length === 0) {
    return (
      <div style={{ padding: '60px 0' }}>
        <Empty
          description="还没有创建任何场景"
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        >
          <AddSceneCard onAdd={onSceneAdd} />
        </Empty>
      </div>
    )
  }

  return (
    <DndProvider backend={HTML5Backend}>
      <div className="scene-grid">
        <Row gutter={[16, 16]}>
          {scenes.map((scene, index) => (
            <Col key={scene.id} {...getColSpan()}>
              <DraggableSceneCard
                scene={scene}
                index={index}
                isSelected={selectedSceneId === scene.id}
                onSelect={onSceneSelect}
                onEdit={onSceneEdit}
                onDelete={onSceneDelete}
                onDuplicate={onSceneDuplicate}
                onPreview={onScenePreview}
                onMove={handleSceneMove}
              />
            </Col>
          ))}
          
          {/* 添加场景卡片 */}
          <Col {...getColSpan()}>
            <AddSceneCard onAdd={onSceneAdd} />
          </Col>
        </Row>
      </div>
    </DndProvider>
  )
}

export default SceneGrid